package com.godyao.framework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.godyao.framework.beans.BeansException;
import com.godyao.framework.beans.PropertyValue;
import com.godyao.framework.beans.PropertyValues;
import com.godyao.framework.beans.factory.*;
import com.godyao.framework.beans.factory.config.BeanDefinition;
import com.godyao.framework.beans.factory.config.BeanPostProcessor;
import com.godyao.framework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import com.godyao.framework.beans.factory.factory.AutowireCapableBeanFactory;
import com.godyao.framework.beans.factory.factory.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 *  实例化Bean类 注册到单例池中并返回
 *  Bean创建时完成前置和后置处理
 * @author missw
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {

    /**
     * 创建策略调用
     */
    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
//    private InstantiationStrategy instantiationStrategy = new SimpleInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Object bean;
        try {
            // 实例化bean  ？ 当构造方法里面有参数怎么办
//            bean = beanDefinition.getBeanClass().getDeclaredConstructor().newInstance();
            // 判断是否返回代理bean对象
            bean = resolveBeforeInstantiation(beanName, beanDefinition);
            if (null != bean) {
                return bean;
            }

            bean = createBeanInstance(beanName, beanDefinition, args);
            // 在设置 Bean 属性之前，允许 BeanPostProcessor 修改属性值
            applyBeanPostProcessorsBeforeApplyingPropertyValues(beanName, bean, beanDefinition);
            // 给bean填充属性
            applyPropertyValues(beanName, bean, beanDefinition);

            // 执行Bean的初始化方法和BeanPostProcessor的前置和后置处理方法
            bean = initialization(beanName, bean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        // 注册实现了DisposableBean接口的Bean对象
        registerDisposableBeanIfNecessary(beanName, bean, beanDefinition);
        // 如果是单例则添加到Spring单例池中
        if (beanDefinition.isSingleton()) {
            registerSingleton(beanName, bean);
        }
        return bean;
    }

    protected void applyBeanPostProcessorsBeforeApplyingPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                PropertyValues pvs = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessPropertyValues(beanDefinition.getPropertyValues(), bean, beanName);
                if (null != pvs) {
                    for (PropertyValue propertyValue : pvs.getPropertyValues()) {
                        beanDefinition.getPropertyValues().addPropertyValue(propertyValue);
                    }
                }
            }
        }
    }

    protected Object resolveBeforeInstantiation(String beanName, BeanDefinition beanDefinition) {
        Object bean = applyBeanPostProcessorsBeforeInstantiation(beanDefinition.getBeanClass(), beanName);
        if (null != bean) {
            bean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
            registerSingleton(beanName, bean);
        }
        return bean;
    }

    private Object applyBeanPostProcessorsBeforeInstantiation(Class beanClass, String beanName) {
        // 处理所有的bean后置处理器
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
                Object bean = ((InstantiationAwareBeanPostProcessor) beanPostProcessor).postProcessBeforeInstantiation(beanClass, beanName);
                if (bean != null) return bean;
            }
        }
        return null;
    }


    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        // 如果不是单例Bean不进行销毁
        if (!beanDefinition.isSingleton()) return;
        if (bean instanceof DisposableBean || StrUtil.isNotBlank(beanDefinition.getDestroyMethodName())) {
            // 存在销毁方法则注册
            registerDisposableBean(beanName,new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }
    }

    private Object initialization(String beanName, Object bean, BeanDefinition beanDefinition) throws Exception {
        // 在执行初始化方法之前，执行所有的跟factory有关感知操作
        if (bean instanceof Aware) {
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware)bean).setBeanFactory(this);
            }
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware)bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ((BeanClassLoaderAware)bean).setBeanClassLoader(getBeanClassLoader());
            }
        }

        // 1.执行BeanPostProcessor Before方法
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);

        // 待完成内容：invokeInitMethods(beanName,wrappedBean,beanDefinition);
        invokeInitMethods(beanName, wrappedBean, beanDefinition);

        // 2.执行BeanPostProcessor After方法
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        return wrappedBean;
    }

    /**
     * 执行初始化方法
     * @param beanName
     * @param wrappedBean
     * @param beanDefinition
     */
    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) throws Exception {
        // 1.实现接口InitializationBean
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }

        // 2.通过解析xml获取init-method
        String initMethodName = beanDefinition.getInitMethodName();
        if (StrUtil.isNotBlank(initMethodName)) {
            Method initMethod = beanDefinition.getBeanClass().getMethod(initMethodName);
            if (null == initMethod) {
                throw new BeansException("Could not find an init method name '" + initMethodName +"' on bean with name '" + beanName +"'");
            }
            initMethod.invoke(wrappedBean);
        }
    }

    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {
            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            for (PropertyValue propertyValue : propertyValues.getPropertyValues()) {
                String name = propertyValue.getName();
                Object value = propertyValue.getValue();
                if (value instanceof BeanReference) {
                    // A依赖B, 获取B的实例化
                    BeanReference beanReference = (BeanReference) value;
                    // 递归 去单例池获取，拿不到则创建
                    value = getBean(beanReference.getBeanName());
                }
                // 填充属性 hutool-all工具包
                try{
                    BeanUtil.setFieldValue(bean, name, value);
                }catch (Exception e) {
                    Method declaredMethod = bean.getClass().getMethod("set" + StrUtil.upperFirst(name), String.class);
                    declaredMethod.setAccessible(true);
                    declaredMethod.invoke(bean ,value);
                }

            }
        } catch (Exception e) {
            throw new BeansException("Error setting property values：" + beanName);
        }
    }


    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Constructor constructorToUser = null;
        Class beanClass = beanDefinition.getBeanClass();
        Constructor[] declaredConstructors = beanClass.getDeclaredConstructors();
        for (Constructor ctor : declaredConstructors) {
            // 实际 Spring 源码中还需要比对入参类型
            if (null != args && ctor.getParameterTypes().length == args.length) {
                constructorToUser = ctor;
                break;
            }
        }
        Object instantiate = instantiationStrategy.instantiate(beanDefinition, beanName, constructorToUser, args);
        applyPropertyValues(beanName, instantiate, beanDefinition);
        return instantiate;
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) {
        Object result = existingBean;
        // 处理所有的bean后置处理器
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postPrecessBeanBeforeInitialization(result, beanName);
            if (null != current) {
                result = current;
            }
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) {
        Object result = existingBean;
        // 处理所有的bean后置处理器
        for (BeanPostProcessor beanPostProcessor : getBeanPostProcessors()) {
            Object current = beanPostProcessor.postProcessBeanAfterInitialization(result, beanName);
            if (null != current) {
                result = current;
            }
        }
        return result;
    }

}
